// 将十六进制字符串转换为字节数组
export function hexStringToByteArray(hexString: string): Uint8Array {
  if (hexString.length % 2 !== 0) {
    throw new Error("Invalid hex string");
  }
  const byteArray = new Uint8Array(hexString.length / 2);
  for (let i = 0; i < hexString.length; i += 2) {
    byteArray[i / 2] = parseInt(hexString.substr(i, 2), 16);
  }
  return byteArray;
};


// CRC校验
export function uartCRC8(hexString: string) {
  const byteArray = hexStringToByteArray(hexString);
  let crc = 0;
  for (let i = 0; i < byteArray.length; i++) {
    crc ^= byteArray[i];
    for (let j = 0; j < 8; j++) {
      if (crc & 0x01) {
        crc = (crc >> 1) ^ 0x8C;
      } else {
        crc >>= 1;
      }
    }
  }
  hexString = hexString + crc.toString(16).padStart(2, "0");
  return hexString;
}

export function isElectron() {
  // 改进的 Electron 环境检测
  return (
    // 主进程或启用了 nodeIntegration 的渲染进程
    (typeof process !== 'undefined' && process.versions?.electron) ||
    // 通过用户代理检测
    (typeof navigator !== 'undefined' && navigator.userAgent?.indexOf('Electron') >= 0)
  );
}

 // 格式化内存使用 - 支持更多单位
 export const formatMemory = (bytes: number) => {
  if (bytes === 0) return "0 B";

  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB", "TB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));

  if (i >= sizes.length) {
    return (
      (bytes / Math.pow(k, sizes.length - 1)).toFixed(2) +
      " " +
      sizes[sizes.length - 1]
    );
  }

  return (bytes / Math.pow(k, i)).toFixed(i >= 2 ? 2 : 0) + " " + sizes[i];
};


// 将日期字符串转换成星期几
export const getWeekDay = (date: string) => {
  const weekDays = ["星期日","星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
  const dateObj = new Date(date);
  const day = dateObj.getDay();
  return weekDays[day];
};